package com.xinz.common;

import com.xinz.Config;
import com.xinz.shared.exception.NetworkException;
import com.xinz.srmi.Log;
import com.xinz.srmi.SrmiClient;
import com.xinz.srmi.impl.DefaultConfigFactory;

/**
 * SRMI客户端连接管理器
 */
public class Connector {

	static Config config = Config.DEFAULT;
	
	private static SrmiClient client;
	
	private static void connect() {
		long start = System.currentTimeMillis();
		try {
			// 添加本地实现，以供Server调用
			client = SrmiClient.createSocket(config.getIp(), config.getPort(), new DefaultConfigFactory());
			client.connect();
		}
		catch(Exception e) {
			throw new NetworkException("网络初始化异常:" + e.getMessage());
		}
		Log.info("connect server use:" + (System.currentTimeMillis() - start));
	}
	
	/**
	 * 为共享接口注册本地实现以供远程server调用
	 * @param interfaceClass
	 * @param implement
	 */
	public static <I,C extends I> void register(Class<I> interfaceClass, C implement) {
		client.getSession().register(interfaceClass, implement);
	}
	
	/**
	 * 解除注册
	 * @param interfaceClass
	 */
	public static <I,C extends I> void deregister(Class<I> interfaceClass) {
		client.getSession().deregister(interfaceClass);
	}
	
	/**
	 * 注册所有obj实现的接口
	 * @param obj
	 */
	public static void registerAll(Object obj) {
		client.getSession().registerAll(obj);
	}
	
	/**
	 * 解除所有注册
	 * @param obj
	 */
	public static void deregisterAll(Class<?> clazz) {
		client.getSession().deregisterAll(clazz);
	}
	
	/**
	 * 获取服务端接口的代理实现
	 * @param clazz 借口类型
	 * @return
	 * @throws Exception 
	 */
	public static <T> T getImplement(Class<T> clazz) {
		if(client == null) {
			connect();
		}
		return client.getImplement(clazz);
	}
}
